package com.youlian.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

public class FileHelper {

	private final static String LOCAL_DUCUMENT_NAME = "vipshop/images";

	public static final class SUFFIX
	{
		public static final String JPG = ".jpg";

		public static final String PNG = ".png";
	}

	/**
	 * 获取文件扩展名
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat( String fileName )
	{
		if( StringHelper.isBlank(fileName) )	return "";

		int point = fileName.lastIndexOf( '.' );
		return fileName.substring( point+1 );
	}

	/**
	 * 根据文件绝对路径获取文件名
	 * @param filePath
	 * @return
	 */
	public static String getFileName( String filePath )
	{
		if( StringHelper.isBlank(filePath) )	return "";
		return filePath.substring( filePath.lastIndexOf( File.separator )+1 );
	}

	/***
	 * ��洢���ļ�
	 * @return
	 * @throws FileNotFoundException
	 */
	public static File getSDCardFile(String filename)
	{
		String path = new File(Environment.getExternalStorageDirectory(),LOCAL_DUCUMENT_NAME).getPath()+"/"+filename;
		File file = new File(path);
		if(Utils.isSDCardAvaiable()){
			return file;
		}else{
			return null;
		}

	}

	public static byte[] resBitmap(Bitmap bm){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	public static File getDataFile(Context mContext,String filename){
		File file = new File(mContext.getFilesDir().getPath());
		if(file.isDirectory()){
			File[] fs = file.listFiles();
			for(File f : fs){
				if(f.getName().equals(filename)){
//					MyLog.error(mContext.getClass(),"找到:"+f.getName());
					return f;
				}
			}
		}
		return null;
	}

	/**
	 * �ļ��Ƿ����
	 * @param filename
	 * @return
	 */
	public static boolean isExists(String filename)
	{
		if(Utils.isSDCardAvaiable()){
			String path = new File(Environment.getExternalStorageDirectory(),LOCAL_DUCUMENT_NAME).getPath()+"/"+filename;
			File file = new File(path);
			if( ! file.exists() || file.isDirectory() || file.length()== 0 ){
				return false;
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
	public static boolean isExists(File file) {
		if (file == null || !file.exists() || file.isDirectory()
				|| file.length() == 0) {
			return false;
		} else {
			return true;
		}
	}

	/***
	 * �����ļ���
	 * @param is
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile(InputStream is,OutputStream os) throws IOException
	{
        	byte[] data = new byte[is.available()];
			is.read(data);
	        os.write(data);
	        is.close();
	        os.close();
	        return true;
	}
	/***
	 * ��ȡ�ļ���
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] openFile(InputStream is) throws IOException
	{
			int size=is.available(); //��ȡ��ĳ���
			byte[] buffer=new byte[size];     //������ȵ��ֽ�����
			is.read(buffer);    //�����е����ݷŵ�buffer������
			is.close();
			return buffer;
	}



	public static byte[] openFile(Context context,String filename) throws IOException
	{
		FileInputStream is = context.openFileInput(filename);
		return openFile(is);
	}


	public static boolean saveFile(Context context,String filename,InputStream is) throws IOException
	{
		FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
		//Context.MODE_APPEND
		return saveFile(is,fos);
	}
	/**
	 *
	 * @param context
	 * @return File
	 */
	public static File getApkFilePath(Context context)
	{
		File file = null;
		try {
			file = new File("/data/data/"+context.getPackageName());
//			file = context.getFilesDir().canRead()
		} catch (Exception e) {
			// TODO: handle exception
		}
		return file;
	}
	/**
	 * 获取文件大小
	 * @param filePath
	 * @return
	 */
	public static long getFileSize( String filePath )
	{
		long size = 0;

		File file = new File( filePath );
		if(file!=null && file.exists())
		{
			size = file.length();
		}
		return size;
	}

	/**
	 * 获取文件大小
	 * @param size 字节
	 * @return
	 */
	public static String getFileFormatSize(long size)
	{
		if (size <= 0)	return "0";
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float)size / 1024;
		if (temp >= 1024)
		{
			return df.format(temp / 1024) + "M";
		}
		else
		{
			return df.format(temp) + "K";
		}
	}

	public static String getFileKB(long size){
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float)size / 1024;
		return df.format(temp) + "K";
	}
	/***
	 * ��ȡ��洢����ļ�
	 * @param dirname
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static byte[] openFile(String filename) throws IOException
	{
			File file = getSDCardFile(filename);
			FileInputStream is = new FileInputStream(file);
			return openFile(is);
	}
	/***
	 * �����ļ�����洢��
	 * @param dirname
	 * @param filename
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static boolean saveFile(String filename,InputStream is) throws IOException
	{
			File file = getSDCardFile(filename);
			FileOutputStream os = new FileOutputStream(file);
			return saveFile(is, os);
	}
	/**
	 *
	 * @param bm
	 * @param url
	 */
	public static void saveFile(Bitmap bm, String url) {
		try {
			String filename = FileHelper.getDownfileName(url);
			File file = new File(YoulianApplication.cacheDir, filename);
			MyLog.error(FileHelper.class,
					"===============保存文件成功:==============:" + file.getName());
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
			file = null;
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
	}
	public static String getDownfileName(String fileUrl) {
		String s1 = fileUrl.substring(fileUrl.lastIndexOf('/') + 1,
				fileUrl.length());
		// String returnUrl = s1.substring(0, s1.indexOf('.'));
		return s1;
	}
	/**
	 * ɾ����洢����ļ�
	 * @param filename
	 * @return
	 *
	 */
	public static boolean removeFile(String filename)
	{
		File file = getSDCardFile(filename);
		if(file != null ){
			return file.delete();
		}else{
			return false;
		}
	}

	public static void removeFiles(String dir,FileFilter filter){
		File file = getSDCardFile(dir);
		if(file != null){
			File[] files = file.listFiles(filter);
			if(files!=null && files.length != 0){
				for(File f:files){
					removeDir(f);
				}
			}
		}
	}

	public static void removeDir(File file){
		if(file.isDirectory()){
			File[] fs = file.listFiles();
			for(File f : fs){
				if(f.exists())
					removeDir(f);
			}
		}

	}

	public static String getSuffix(String filename)
	{
		try {
			int beginIndex = filename.lastIndexOf(".");
			String result = filename.substring(beginIndex).trim();
			int length = result.length();
			if(length > 0 && length < 5){
				return result;
			}else{
				return "";
			}
		} catch (Exception e) {
			return "";
		}
	}

}
